import socket


class Server:
    def __init__(self, ip_addr, port):
        self.addr = (ip_addr, port)
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.bind(self.addr)

    def write(self, message):
        self.tcp_socket.sendall(message)

    def read(self, conn_socket, client_addr):
        message = conn_socket.recv(1024)
        print(f"server Received {message!r}")
        message, client_addr = message
        self.write(message.encode("utf8"))
        print("finished socket echoing to", client_addr)

    def run(self):
        self.tcp_socket.listen()
        conn, addr = self.tcp_socket.accept()
        while True:
            try:
                self.read(conn, addr)
            except KeyboardInterrupt:
                return


class Client:
    def __init__(self, ip_addr, port):
        self.addr = (ip_addr, port)
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def read(self):
        message = self.tcp_socket.recv(1024)
        return message
    
    def write(self, message):
        self.tcp_socket.sendall(message)

    def run(self):
        while True:
            try:
                message = str(input("input the message you want to echo in the form of message,ip address, port:\n"))
                message, ip, port = message.split(",")
                server_add = (ip, int(port))
                self.tcp_socket.connect(server_add)
                self.write(message.encode("utf8"))
                print("finished socket writing")
                echo_message = self.read()
                print(f"Received {message!r}")
                self.tcp_socket.close()
            except KeyboardInterrupt:
                return


if __name__ == "__main__":
    #server = Server("127.0.0.1", 65431)
    server = Server("222.28.86.39", 65431)
    server.run()
    #client = Client("127.0.0.1", 65432)
    
    #client.run()
